/**
 * type: 微信活动
 * des：百度语音合成封装.
 * by: Xie Xiaofei
 * created: 2017/9/27
 * lastupdate: 2017/9/27
 * 
 * url: /api/speech
 * method: get
 * body: text
 * return: {url}    //  语音地址
 */


var path = require('path')
var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var fs = require('fs');
var AipSpeechClient = require('../common/baidu/index.js').speech;
// 设置APPID/AK/SK
var APP_ID = "10194393";
var API_KEY = "OHY7oTsIVQs3Dq8wv1TAU2SB";
var SECRET_KEY = "jQlxgzIq74fneiLI2Rza0BTHAlVX6gc3";

var client = new AipSpeechClient(APP_ID, API_KEY, SECRET_KEY);


var Dal = require('../../utils/index.js').Dal
var SqlHelper = require('../../utils/index.js').SqlHelper

var sqlHelper = new SqlHelper('speech');;

var getAudioByText = function (text) {
    return new Promise((resolve, reject) => {
        sqlHelper.select({ text: text }, function (results) {
            resolve(results)
        })
    });
}

var pushAudio = function (data) {
    return new Promise((resolve, reject) => {
        sqlHelper.insert(data, function (results) {
            resolve(results)
        })
    });
}

const getAudio = async function (req, res, next) {
    var body = req.body || req.query;
    var text = body.text;

    // 根据文字搜索数据库里面有没有
    let results = await getAudioByText(text);
    if (results.length > 0) {
        console.log('数据库服务器查询成果...' + results[0].filename)
        return res.send({ uri: results[0].filename, code: 1 });
    }

    // 重新请求
    let result = await client.text2audio(text);
    console.log(result)
    if (result.data) {
        var time = new Date();
        var rand = time.getTime() + Math.floor(Math.random() * 100)
        var fileName = rand + '.mp3';
        fs.writeFileSync('/home/mydisk/www/mp3/' + fileName, result.data);
        // fs.writeFileSync( fileName, result.data);
        pushAudio({ text: text, filename: fileName });// 存放在数据库，避免重新请求, 减少并发
        console.log('远程服务器请求成功....' + fileName)
        return res.send({ uri: fileName, code: 1 });
    } else {
        console.log('查询失败...' + result.err_no);
        return res.send({ code: 0, msg: '调用失败' });
    }
}

server.get({ path: routerApi, name: routerApi }, getAudio)
